<template>
	<wd-popup v-model="show" position="bottom" :z-index="999" closable safe-area-inset-bottom>
		<view class="poupu-title"> 新增预警 </view>
		<wd-form ref="form" :model="formData">
			<wd-picker 
				:columns="skuList" 
				label="选择商品" 
				value-key="id" 
				label-key="label" 
				v-model="formData.sku_id"
				prop="sku_id"
				:rules="[{ required: true, message: '请选择商品' }]"
			/>
			<wd-input
				type="number"
				label="预警阈值"
				v-model="formData.warning_threshold"
				prop="warning_threshold"
				placeholder="请输入阈值"
				:rules="[{ required: true, message: '请输入阈值值' }]"
			/>
			<wd-textarea
				label="备注信息"
				v-model="formData.remark"
				placeholder="请填写备注信息"
			/>
		</wd-form>
		<view class="btn-box justify-center">
			<wd-button class="btn" @tap="confirm"> 确 认 </wd-button>
		</view>
	</wd-popup>
</template>

<script setup>
	import { ref } from 'vue'
	import { useUserStore } from '@/store'
	import { toWarehouseApi, addWarningApi } from '@/api'
	const emit = defineEmits(['addSuccess'])
	const show = ref(false)
	const form = ref()
	const skuId = ref(null)
	const skuList = ref([])
	const formData = ref({
		sku_id: '',
		warning_threshold: '',
		remark: ''
	})
	const pickSku = (id) => {
		skuId.value = id
	}
	const confirm = () =>{
		const { userInfo } = useUserStore()
		const { sku_id, warning_threshold, remark } = formData.value
		form.value.validate().then(({ valid })=> {
			const params = {
				sku_id,
				remark,
				warning_threshold,
				uid: userInfo.uid
			}
			if(valid) {
				addWarningApi(params).then(res =>{
					close()
					uni.showToast({ icon: 'none', title: '添加成功' })
					emit('addSuccess')
				}).catch(err => {
					uni.showToast({ icon: 'none', title: err.msg })
				})
			}
		})
	}
	const open = () =>{
		show.value = true
		addWarningApi({}, 'GET').then(res => {
			skuList.value = res
			if(!skuList.value.length) return
			skuList.value.forEach(item => {
				item.label = item.product_name + '-sku: ' + item.sku
			})
		})
	}
	const close = () => {
		show.value = false
	}
	defineExpose({
		open,
		close
	})
</script>

<style lang="scss" scoped>
	:deep(.wd-popup) {
		padding: 20rpx !important;
		border-radius: 20rpx 20rpx 0 0;
		.poupu-title {
			font-size: 32rpx;
			font-weight: bold;
			text-align: center;
			margin-bottom: 20rpx;
		}
		.wd-textarea__label-inner {
			margin-left: 12px;
		}
		.uni-textarea-textarea, .wd-textarea__placeholder {
			border-radius: 20rpx;
			border: 1px solid #eee;
			padding: 20rpx !important;
		}
		.btn-box {
			margin-top: 30rpx;
			.btn {
				width: 100%;
			}
		}
	}
</style>